package com.momo.mal.anime.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

import net.momo.mal.R;
import com.momo.mal.anime.view.AnimeView;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.util.AnimeUtil;

public class AnimeListAdapter extends BaseAdapter {
	private List<Anime> animes = new ArrayList<Anime>();
	private LayoutInflater mInflater;
	private Activity activity;
	private MalDatabaseAdapter dbAdapter;

	public AnimeListAdapter(Activity activity, List<Anime> animes) {
		mInflater = (LayoutInflater) activity
				.getSystemService(activity.LAYOUT_INFLATER_SERVICE);
		dbAdapter = new MalDatabaseAdapter(activity);
		
		this.animes = animes;
		this.activity = activity;
	}

	@Override
	public int getCount() {
		return animes.size();
	}

	@Override
	public Object getItem(int location) {
		return animes.get(location);
	}

	@Override
	public long getItemId(int location) {
		return location;
	}

	@Override
	public View getView(final int location, View view, ViewGroup viewgroup) {
		ViewHolder holder;
		if (view == null) {
			holder = new ViewHolder();

			view = mInflater.inflate(R.layout.anime_list_adapter, null);

			holder.title = (TextView) view.findViewById(R.id.text_title);
			holder.type = (TextView) view.findViewById(R.id.text_type);
			holder.episode = (TextView) view.findViewById(R.id.text_episode);
			holder.score = (TextView) view.findViewById(R.id.text_score);
			holder.linearView = (LinearLayout) view.findViewById(R.id.linear_view);
			holder.linearMore = (LinearLayout) view.findViewById(R.id.linear_more);
			holder.priority = (TextView) view.findViewById(R.id.text_priority);
			holder.buttonMore = (ImageButton) view
					.findViewById(R.id.image_button_edit_status);

			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		if (location % 2 == 0) {
			view.setBackgroundColor(Color.WHITE);
		} else {
			view.setBackgroundColor(Color.rgb(217, 229, 250));
		}
		
		if (animes.get(location).getStatus()
				.equalsIgnoreCase("currently airing")) {
			holder.title.setText(Html.fromHtml("<b>"
					+ animes.get(location).getTitle() + "</b>&nbsp;(Airing)"));
		} else if(animes.get(location).getStatus()
				.equalsIgnoreCase("not yet aired")) {
			holder.title.setText(Html.fromHtml("<b>"
					+ animes.get(location).getTitle() + "</b>&nbsp;(Not yet aired)"));
		} else {
			holder.title.setText(Html.fromHtml("<b>"
					+ animes.get(location).getTitle() + "</b>"));
		}
		holder.type.setText("Type : " + animes.get(location).getType());
		holder.episode.setText("Eps : "
				+ animes.get(location).getWatchedEpisode() + "/"
				+ animes.get(location).getEpisode());
		holder.score.setText("Score : " + animes.get(location).getScore());
		
		if(animes.get(location).getPriority() != null) {
			if(animes.get(location).getPriority().equals("0")) {
				holder.priority.setText(Html.fromHtml("Prio : <font color='green'>Low</font>"));
			}
			if(animes.get(location).getPriority().equals("1")) {
				holder.priority.setText(Html.fromHtml("Prio : <font color='yellow'>Med</font>"));
			}
			if(animes.get(location).getPriority().equals("2")) {
				holder.priority.setText(Html.fromHtml("Prio : <font color='red'>High</font>"));
			}
		} else {
			holder.priority.setText(Html.fromHtml("Prio : <font color='green'>Low</font>"));
		}
		
		holder.buttonMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
					onClickPopUpMenu(view, location, animes.get(location).getTitle(), animes.get(location).getId());
			}
		});
		
		holder.linearMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
					onClickPopUpMenu(view, location, animes.get(location).getTitle(), animes.get(location).getId());
			}
		});
		
		holder.linearView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(activity, AnimeView.class);
				intent.putExtra("anime_id", animes.get(location).getId());
				intent.putExtra("title", animes.get(location).getTitle());
				activity.startActivity(intent);
			}
		});
		
		return view;
	}
	
	private class ViewHolder {
		public LinearLayout linearView;
		public LinearLayout linearMore;
		public TextView title;
		public TextView type;
		public TextView episode;
		public TextView score;
		public TextView priority;
		public ImageButton buttonMore;
	}
	
	private void onClickPopUpMenu(View view, final int location, final String title, final String id) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			PopupMenu popup = new PopupMenu(activity, view);
			if(animes.get(location).getWathcedStatus().equalsIgnoreCase("watching")) {
				popup.getMenuInflater().inflate(R.menu.menu_anime_edit_list_watching,
						popup.getMenu());
			} else {
				popup.getMenuInflater().inflate(R.menu.menu_anime_edit_list,
						popup.getMenu());
			}
			
			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
	
				@Override
				public boolean onMenuItemClick(MenuItem item) {
					// TODO Auto-generated method stub
					if (item.getItemId() == R.id.menu_add_episode) {
						Anime anime = dbAdapter.getAnimeById(animes.get(location).getId());
						int watched = Integer.parseInt(anime.getWatchedEpisode()) + 1;
						if(anime.getEpisode().equals(String.valueOf(watched))) {
							anime.setWathcedStatus("completed");
							Toast.makeText(activity, "You've completed watch " + anime.getTitle(), Toast.LENGTH_LONG).show();
						}
						anime.setWatchedEpisode(String.valueOf(watched));
						new AnimeUtil().new RequestAnimeUpdate(activity, dbAdapter.hasAnime(anime.getId())).execute(anime);
					}
					if (item.getItemId() == R.id.menu_edit) {
						Anime anime = dbAdapter.getAnimeById(animes.get(location).getId());
						AnimeUtil.animeAddOrUpdatePopUp(anime, activity);
					}
					if (item.getItemId() == R.id.menu_more) {
						Intent intent = new Intent(activity, AnimeView.class);
						intent.putExtra("anime_id", id);
						intent.putExtra("title", title);
						activity.startActivity(intent);
					}
					if (item.getItemId() == R.id.menu_delete) {
						AlertDialog.Builder builder = alertDialogDelete(activity, title, id);
						builder.create().show();
					}
					if (item.getItemId() == R.id.menu_share) {
						Intent intent = new Intent(Intent.ACTION_SEND);
						intent.setType("text/plain");
						intent.putExtra(Intent.EXTRA_SUBJECT, "Recommend from your friend");
						intent.putExtra(Intent.EXTRA_TEXT, "This is recommend for you. You should try " + title + ". http://myanimelist.net/anime/" + id);
						intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - " + title);
	
						activity.startActivity(Intent.createChooser(intent, "Share Via ..."));
					}
					return false;
				}
	
			});
			
			popup.show();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			Resources res = activity.getResources();
			
			builder.setTitle(res.getString(R.string.menu_title));
			if(animes.get(location).getWathcedStatus().equalsIgnoreCase("watching")) {
				String[] items = new String[] {res.getString(R.string.menu_add_episode),
					res.getString(R.string.menu_edit),
					res.getString(R.string.menu_delete),
					res.getString(R.string.menu_share), 
					res.getString(R.string.menu_information) };
				
				builder.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0) {
							Anime anime = dbAdapter.getAnimeById(animes.get(location).getId());
							int watched = Integer.parseInt(anime.getWatchedEpisode()) + 1;
							if(anime.getEpisode().equals(String.valueOf(watched)) || watched > Integer.parseInt(anime.getEpisode())) {
								anime.setWathcedStatus("completed");
								anime.setWatchedEpisode(anime.getEpisode());
								Toast.makeText(activity, "You've completed watch " + anime.getTitle(), Toast.LENGTH_LONG).show();
							} else {
								anime.setWatchedEpisode(String.valueOf(watched));
							}
							
							new AnimeUtil().new RequestAnimeUpdate(activity, dbAdapter.hasAnime(anime.getId())).execute(anime);
						}
						if(which == 1) {
							Anime anime = dbAdapter.getAnimeById(animes.get(location).getId());
							AnimeUtil.animeAddOrUpdatePopUp(anime, activity);
						}
						if(which == 2){
							AlertDialog.Builder builder = alertDialogDelete(activity, title, id);
							builder.create().show();
						}
						if(which == 3){
							Intent intent = new Intent(Intent.ACTION_SEND);
							intent.setType("text/plain");
							intent.putExtra(Intent.EXTRA_SUBJECT, "Recommend from your friend");
							intent.putExtra(Intent.EXTRA_TEXT, "This is recommend for you. You should try " + title + ". http://myanimelist.net/anime/" + id);
							intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - " + title);
		
							activity.startActivity(Intent.createChooser(intent, "Share Via ..."));
						}
						if(which == 4) {
							Intent intent = new Intent(activity, AnimeView.class);
							intent.putExtra("anime_id", id);
							intent.putExtra("title", title);
							activity.startActivity(intent);
						}
					}
				});
			} else {
				String[] items = new String[] {
						res.getString(R.string.menu_edit),
						res.getString(R.string.menu_delete),
						res.getString(R.string.menu_share), 
						res.getString(R.string.menu_information) };
				
				builder.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0) {
							Anime anime = dbAdapter.getAnimeById(animes.get(location).getId());
							AnimeUtil.animeAddOrUpdatePopUp(anime, activity);
						}
						if(which == 1){
							AlertDialog.Builder builder = alertDialogDelete(activity, title, id);
							builder.create().show();
						}
						if(which == 2){
							Intent intent = new Intent(Intent.ACTION_SEND);
							intent.setType("text/plain");
							intent.putExtra(Intent.EXTRA_SUBJECT, "Recommend from your friend");
							intent.putExtra(Intent.EXTRA_TEXT, "This is recommend for you. You should try " + title + ". http://myanimelist.net/anime/" + id);
							intent.putExtra(Intent.EXTRA_TITLE, "Momo MAL - " + title);
		
							activity.startActivity(Intent.createChooser(intent, "Share Via ..."));
						}
						if(which == 3) {
							Intent intent = new Intent(activity, AnimeView.class);
							intent.putExtra("anime_id", id);
							intent.putExtra("title", title);
							activity.startActivity(intent);
						}
					}
				});
			}
			
			builder.create().show();
		}
	}

	private Builder alertDialogDelete(final Activity activity, String title, final String animeId) {
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setTitle("Delete " + title);
		builder.setMessage(Html.fromHtml("Are you sure to delete ?"))
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   new AnimeUtil().new RequestAnimeDelete(activity).execute(new String[] {animeId});
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
	
		return builder;
	}
	
}